<template>
  <div class="search">
    <h1>设备分类管理</h1>
    <hr style="border: 1px solid rgb(240, 240, 240)" />
    <span>设备分类名称</span>
    <el-input
      v-model="searchParams.group"
      style="width: 200px; margin-right: 40%"
      placeholder="请输入"
    />
    <el-button type="primary" @click="fetchData">查询</el-button>
    <el-button type="default" @click="resetSearch">重置</el-button>
  </div>
  <div class="page">
    <div class="page-header">
      <div class="page-header-left">
        <span>储物室列表</span>
      </div>
      <div class="page-header-right">
        <el-button
          type="primary"
          style="margin-top: 1rem"
          @click="openCreateDialog"
          >+&nbsp;新建</el-button
        >
        <el-button
          type="default"
          style="margin-top: 1rem; margin-right: 3rem"
          @click="deleteDialog = true"
          >批量删除</el-button
        >
        <el-dialog v-model="deleteDialog" title="警告" width="500" align-center>
          <span>是否删除选中的信息，该操作不可撤回！</span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteDialog = false">取消</el-button>
              <el-button type="primary" @click="deleteByIds"> 确认 </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column property="group" label="设备分类名称" />
      <el-table-column property="status" label="状态" />
      <el-table-column property="adder" label="添加人" />
      <el-table-column property="addTime" label="添加时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" size="small" @click="editRow(scope.row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="deleteRow(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:current-page="searchParams.page"
        v-model:page-size="searchParams.pageSize"
        :page-sizes="[5, 10, 20]"
        style="margin-bottom: 2rem"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>

  <!-- 新建设备分类弹窗 -->
  <el-dialog title="新增设备分类" v-model="dialogVisible" width="30%">
    <el-input
      v-model="newGroup"
      placeholder="请输入设备分类名称"
      style="width: 100%; margin-bottom: 20px"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="createGroup">确定</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus"; // 引入Element UI的消息组件

const loading = ref(false);
const deleteDialog = ref(false);
const selectRows = ref([]);

// 搜索参数
const searchParams = reactive({
  group: "", // 设备分类名称
  page: 1, // 当前页码
  pageSize: 10, // 每页显示记录数
});

// 新建设备分类相关数据
const dialogVisible = ref(false); // 控制弹窗显示
const newGroup = ref(""); // 输入的新设备分类名称

// 数据
const tableData = ref([]);
const total = ref(0);

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const response = await axios.get("http://localhost:8080/DeviceGroup/page", {
      headers: {
        Authorization: localStorage.getItem("token"),
      },
      params: searchParams,
    });
    const result = response.data;

    if (result.code === 1 && result.data) {
      tableData.value = result.data.records || []; // 当前页数据集合
      total.value = result.data.total || 0; // 总记录数
      loading.value = false;
    } else {
      console.error(result.msg || "查询失败");
    }
  } catch (error) {
    console.error("请求失败", error);
  }
};

// 重置搜索条件
const resetSearch = () => {
  searchParams.group = "";
  searchParams.page = 1;
  searchParams.pageSize = 10;
  fetchData();
};

const handleSelectionChange = (selectedRows) => {
  selectRows.value = selectedRows;
};

// 分页操作
const handleSizeChange = (newSize) => {
  searchParams.pageSize = newSize;
  fetchData();
};

const handlePageChange = (newPage) => {
  searchParams.page = newPage;
  fetchData();
};

// 编辑行
const editRow = (row) => {
  console.log("编辑行数据", row);
  router.push({
    path: "/backend/equipment/newGroup",
    query: { id: row.id },
  });
};

// 删除行
const deleteRow = async (row) => {
  console.log("删除行数据", row);
  try {
    const response = await axios.delete(
      `http://localhost:8080/DeviceGroup/${row.id}`,
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
      }
    );
    const result = response.data;

    if (result.code === 1) {
      ElMessage.success("删除成功");
      fetchData();
    } else {
      ElMessage.error(result.msg || "删除失败");
    }
  } catch (error) {
    console.error("删除失败", error);
    ElMessage.error("删除失败");
  }
};

const deleteByIds = () => {
  if (selectRows.value.length === 0) {
    ElMessage({
      message: "请选择要删除的信息",
      type: "warning",
    });
    deleteDialog.value = false;
    return;
  }

  const config = {
    url: "http://localhost:8080/DeviceGroup/deleteByIds",
    method: "DELETE",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
    data: selectRows.value.map((item) => item.id),
  };

  const response = axios(config);
  response
    .then((data) => {
      if (data.data.code === 1) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        setTimeout(() => {
          fetchData();
        }, 2000);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  deleteDialog.value = false;
};

// 新建设备分类弹窗
const openCreateDialog = () => {
  dialogVisible.value = true; // 打开弹窗
};

const createGroup = async () => {
  if (!newGroup.value.trim()) {
    ElMessage.error("设备分类名称不能为空");
    return;
  }

  try {
    const groupName = encodeURIComponent(newGroup.value.trim()); // 防止特殊字符问题
    const response = await axios.post(
      `http://localhost:8080/DeviceGroup/${groupName}`,
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
      }
    );
    const result = response.data;

    if (result.code === 1) {
      ElMessage.success(result.msg || "新增成功");
      dialogVisible.value = false; // 关闭弹窗
      newGroup.value = ""; // 清空输入框
      fetchData(); // 刷新数据
    } else {
      ElMessage.error(result.msg || "新增失败");
    }
  } catch (error) {
    console.error("新增失败", error);
    ElMessage.error("新增失败");
  }
};

// 页面加载时自动获取数据
onMounted(fetchData);
</script>

<style scoped>
.search {
  background-color: white;
  padding-bottom: 2rem;
  height: auto;
  margin-top: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin-top: 2rem;
  margin-left: 3rem;
  margin-right: 1rem;
  height: 24px;
}

.page {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  margin-top: 2rem;
  justify-content: center;
}
</style>
